﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.Framework.Net;
using ZyGames.Framework.RPC.Sockets;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 通过桌子编号进入房间
	/// </summary>
	public class Action10027 : BaseAction
	{
		private int _userId;
		private int _tableId;
		private TableData _currentTable;
		private bool _result = false;
		private GameUser _currentGameUser;

		public Action10027(HttpGet actionGetter)
			: base((short)ActionType.DZApplyEnterInsuranceRoomByTableID, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref _tableId) &&
				httpGet.GetInt("UserID", ref _userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			try
			{
				this._currentGameUser = GameTable.Current.GetUser(_userId);
				if (_currentGameUser == null)
				{
					Tool.WriteWarmingLine("10039当前玩家不存在");
					return false;
				}

				var roomData = GameRoom.Current.GetRoomData(1001);
				foreach (var pair in roomData.Tables)
				{
					var table = pair.Value;
					if (table.TableId == _tableId)
					{
						_currentTable = table;
						break;
					}
				}
				if (_currentTable == null)
				{
					Tool.WriteWarmingLine(string.Format("消息10027获得房间id:{0}不存在", _tableId));
					return false;
				}
				//判断是否勾选了不允许旁观功能
				if (_currentTable.CanNotOnLooking)
				{
					Tool.WriteWarmingLine("不允许旁观");
					return false;
				}
				var roomInfo = GameRoom.Current.GetRoom(ConfigEnvSet.GetInt("GameSetting.DefaultRoomID", 1001));
				if (roomInfo == null)
					return false;
				GameRoom.Current.JoinTable(_currentGameUser, roomInfo, _currentTable);
				//强制重置位置跟Ready状态，不知道哪儿改变了
				//_currentGameUser.Property.ResetState(_tableId);
				_result = true;
				return true;
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine("10027消息异常:" + ex.ToString());
				return false;
			}
		}

		public override void TakeActionAffter(bool state)
		{
			//进入保险人页面
			if (_currentTable != null && _result)
			{
				var userList = ClientNotifier.GetUserList(_currentTable);

				var newlist = new List<IUser>();
				newlist.Add(new SessionUser(_currentGameUser));
				var newParams = new Parameters();
				var tableInfo = Convert.ToBase64String(ProtoBufUtils.Serialize(_currentTable));
				newParams["TableData"] = tableInfo;
				newParams["TableMasterName"] = _currentTable.TableMaster.NickName;
				newParams["TableMasterUserID"] = _currentTable.TableMaster.UserId;
				//向申请进入房间的人发送其他玩家和房间信息
				ActionFactory.SendAction(newlist, (int)ActionType.DZNotifyOtherInfoForMe, newParams, (asyncResult) =>
				{
					Console.WriteLine("Action 10041 向申请进入房间的人发送其他玩家和房间信息 send result:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail");
				});

				var list = new List<IUser>();
				foreach (var user in userList)
				{
					//排除掉当前进入房间的人
					if (user.GetUserId() != _currentGameUser.GetUserId())
						list.Add(new SessionUser(user));
				}
				var parameters = new Parameters();
				parameters["TableID"] = _tableId;
				parameters["UserID"] = _userId;
				parameters["NickName"] = _currentGameUser.NickName;
				parameters["HeadIcon"] = _currentGameUser.HeadIcon;
				parameters["HeadIconBytes"] = _currentGameUser.HeadIconBytes;
				ActionFactory.SendAction(list, (int)ActionType.DZBroadcastApplyEnterInsuranceRoomByInviteNum, parameters, (asyncResult) =>
				{
					Console.WriteLine("Action 10040 广播某玩家通过邀请码进入保险页面 send result:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail");
				});
			}
			base.TakeActionAffter(state);
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(_result);
		}
	}
}
